import 'package:flutter/foundation.dart';
import 'package:hxdj/common/env_config/env.dart';
import 'package:hxdj/common/my_constant.dart';
import 'package:hxdj/common/utils/my_event_bus_util.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'dart:convert';

class RCEngineManager {
  static final RCEngineManager _instance = RCEngineManager._internal();

  //融云的实体
  RCIMIWEngine? engine;
  RCEngineManager._internal();
  factory RCEngineManager() => _instance;

  //IM的链接状态
  RCIMIWConnectionStatus? imConnectionStatus = RCIMIWConnectionStatus.unconnected;

//初始化融云的引擎
  Future<RCIMIWEngine?> initRongClound() async {
    RCIMIWEngineOptions options = RCIMIWEngineOptions.create();
    String rcAppkey = Env.getInstance()!.rcAppkey;
    engine = await RCIMIWEngine.create(rcAppkey, options);

    if (engine != null) {
      debugPrint("初始化融云成功");
    }

    //监听融云的链接状态等
    setListener();
    return engine;
  }

  //登录IM
  Future<bool> connectIM(String token, {RCIMIWConnectCallback? callback}) async {
    int? code = await engine!.connect(token, 10, callback: callback);
    return code == 0 ? true : false;
  }

  //断开连接
  Future<bool> disconnectIM() async {
    /// - [receivePush] 退出后是否接收 push，true:断开后接收远程推送，false:断开后不再接收远程推
    int? code = await engine!.disconnect(true);
    return code == 0 ? true : false;
  }

  String formatJson(jsonObject) {
    if (jsonObject == null) {
      return "";
    }
    const JsonEncoder encoder = JsonEncoder.withIndent('    ');
    return encoder.convert(jsonObject);
  }

  //设置监听,
  setListener() async {
    //监听融云的连接状态
    engine?.onConnectionStatusChanged = (RCIMIWConnectionStatus? status) {
      imConnectionStatus = status;
      debugPrint("连接状态:$status");
      MyEventBusUtil.sentEvent(MyEventBusHelp(MyEventBusTag.onConnectionStatusChanged));
    };

    //接收消息
    engine?.onMessageReceived = (RCIMIWMessage? message, int? left, bool? offline, bool? hasPackage) {
      Map<String, String> arg = {};
      arg["listener"] = "onMessageReceived";
      arg["message"] = formatJson(message?.toJson());
      arg["left"] = left.toString();
      arg["offline"] = offline.toString();
      arg["hasPackage"] = hasPackage.toString();
      MyEventBusUtil.sentEvent(MyEventBusHelp(MyEventBusTag.onMessageReceived, result: arg));
    };
  }

  //获取用户的的多个会话
  Future<bool> getRecentConversationList({IRCIMIWGetConversationsCallback? callback}) async {
    int? code = await engine!.getConversations([RCIMIWConversationType.private], "", 0, 50, callback: callback);
    return code == 0 ? true : false;
  }

  //获取用户的未读消息的会话列表
  Future<bool> getUnreadConversations({IRCIMIWGetUnreadConversationsCallback? callback}) async {
    int? code = await engine!.getUnreadConversations([RCIMIWConversationType.private], callback: callback);
    return code == 0 ? true : false;
  }

  ///获取与某人的消息记录 加载历史消息
  Future<bool> getMessages(String targetId, {int? timestamp, IRCIMIWGetMessagesCallback? callback}) async {
    if (timestamp == null) {
      DateTime now = DateTime.now();
      // 将DateTime对象转换为时间戳（秒）
      timestamp = now.millisecondsSinceEpoch;
    }

    int? code = await engine!.getMessages(RCIMIWConversationType.private, targetId, null, timestamp,
        RCIMIWTimeOrder.before, RCIMIWMessageOperationPolicy.local, MyConstant.messagePageSize,
        callback: callback);
    return code == 0 ? true : false;
  }

  ///获取所有未读数
  Future<int> getTotalUnreadCount({IRCIMIWGetTotalUnreadCountCallback? callback}) async {
    int? code = await engine!.getTotalUnreadCount(null, callback: callback);
    return code;
  }

  /// 获取某个会话
  Future<int> getConversation(String targetId, {IRCIMIWGetConversationCallback? callback}) async {
    return await engine!.getConversation(RCIMIWConversationType.private, targetId, null, callback: callback);
  }

  /// 清除某个会话中的未读消息数。
  Future<int> clearUnreadCount(String targetId, int timestamp, {IRCIMIWClearUnreadCountCallback? callback}) async {
    return engine!
        .clearUnreadCount(RCIMIWConversationType.private, targetId, null, timestamp + 5000, callback: callback);
  }

  /// 发送普通消息
  Future<int> sendTextMessage(String targetId, String text, {RCIMIWSendMessageCallback? callback}) async {
    RCIMIWTextMessage? textMessage = await engine!.createTextMessage(
      RCIMIWConversationType.private,
      targetId,
      "",
      text,
    );
    textMessage!.expansion = {};
    return await engine!.sendMessage(textMessage, callback: callback);
  }

  ///删除某一个会话
  Future<int> removeConversation(String targetId, {IRCIMIWRemoveConversationCallback? callback}) async {
    return engine!.removeConversation(RCIMIWConversationType.private, targetId, null, callback: callback);
  }
}
